package com.tuo51.manager.controller;


import com.tuo51.core.domain.org.Organization;
import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.core.repositories.StaffRepository;
import com.tuo51.core.service.StaffService;
import com.tuo51.evaluate.vo.users.StaffVO;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.manager.service.DataAnalysisService;
import com.tuo51.manager.vo.StaffListItemVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tuo51.foudation.constant.RequestConstant.TICKET;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 附近的合作伙伴
 */
@RestController
@RequestMapping("/mapi/users")
@Api(value = "/mapi/users", tags = "OP - 用户相关")
public class MAPIUsersController {

    @Autowired
    DataAnalysisService analysisService;

    @Autowired
    StaffService staffService;

    @Autowired
    StaffRepository staffRepository;

    @Autowired
    MemVerificationCache cache;

    @RequestMapping(value = "/list", method = GET)
    @ApiOperation(value = "查询复合用户信息列表, 仅机构")
    public StatusResponse userComplexlist(@RequestHeader(TICKET) String ticket,
                                   @RequestParam(value = "pageNum", required = false, defaultValue = "0")Integer pageNum,
                                   @RequestParam(value = "pageSize", required = false, defaultValue = "15")Integer pageSize,
                                   @RequestParam(value = "searchBy", required = false) String searchBy){

        String staffId = cache.getStaffId(ticket);

        long totalItems = analysisService.countUsersPage(searchBy);

        List<StaffListItemVO> users = analysisService.getUsersPage(pageNum, pageSize, searchBy);

        Page<StaffListItemVO> ret = new PageImpl<>(users, PageRequest.of(pageNum, pageSize), totalItems);

        return StatusResponse.success(ret);
    }

    @RequestMapping(value = "/staff_list", method = GET)
    @ApiOperation(value = "查询用户列表")
    public StatusResponse userlist(@RequestHeader(TICKET) String ticket,
                                   @RequestParam(value = "pageNum", required = false, defaultValue = "0")Integer pageNum,
                                   @RequestParam(value = "pageSize", required = false, defaultValue = "15")Integer pageSize,
                                   Integer platform,
                                   String sourceAppId,
                                   @RequestParam(value = "orderBy", required = false)String orderBy,
                                   @RequestParam(value = "searchBy", required = false) String searchBy){


        cache.getStaffId(ticket);

        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);

        Page<Staff> ret = staffRepository.findAll(new Specification<Staff>() {
            @Override
            public Predicate toPredicate(Root<Staff> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                Predicate base = cb.isFalse(root.get("deleted"));

                if (StringUtils.isNotEmpty(searchBy)){
                    String key = "%" + searchBy + "%";
                    Predicate p = cb.or(cb.like(root.get("mobile"), key),
                            cb.like(root.get("realName"), key),
                            cb.like(root.get("nickName"), key));
                    base = cb.and(base, p);
                }

                if (platform != null){
                    Predicate p = cb.equal(root.get("platform"), platform);
                    base = cb.and(base, p);
                }

                if (sourceAppId != null){
                    Predicate p = cb.equal(root.get("sourceAppId"), sourceAppId);
                    base = cb.and(base, p);
                }

                query.where(base);

                if (StringUtils.isNotEmpty(orderBy)){
                    query.orderBy(cb.asc(root.get(orderBy)));
                }else {
                    query.orderBy(cb.desc(root.get("created")));
                }

                return query.getRestriction();
            }
        }, pageRequest);

        ret.map(k->StaffVO.of(k));

        return StatusResponse.success(ret);
    }

    @RequestMapping(value = "/info", method = GET)
    @ApiOperation(value = "用户详情")
    public StatusResponse userinfo(@RequestHeader(TICKET) String ticket,
                                   @RequestParam(value = "userId", required = true)String userId){

        String staffId = cache.getStaffId(ticket);

        Map ret = new HashMap();

        Staff staff = staffService.getById(userId);
        Organization org = staffService.staffOrgnization(staff);

        ret.put("staff", staff);
        ret.put("org", org);

        return StatusResponse.success(ret);
    }

    @RequestMapping(value = "/edit", method = POST)
    @ApiOperation(value = "用户详情编辑， admin用以指定用户是否为管理员,（仅导入接口开放）")
    public StatusResponse editStaff(@RequestHeader(TICKET) String ticket,
                                    StaffVO staff, int admin){
        cache.getStaffId(ticket);

        Staff ret = null;
        if (StringUtils.isNotEmpty(staff.getId())){
            ret = staffService.getById(staff.getId());
        }

        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "条目不存在");
        }

        ret.setNickName(staff.getNickName());
        ret.setRealName(staff.getRealName());
        ret.setMobile(staff.getMobile());
        ret.setHeadImgUrl(staff.getHeadImgUrl());
        ret.setAdmin(admin);
        ret.setMobile(staff.getMobile());
        ret.setSex(staff.getSex());

        staffRepository.save(ret);

        return StatusResponse.success(ret);
    }
}
